import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../routers/router.js'

// 创建纯净的axios实例
const http = axios.create({
    baseURL: 'http://localhost:6062',
    timeout: 10000
})

// ==================== 拦截器配置 ====================
const setupInterceptors = () => {
    // 请求拦截器
    http.interceptors.request.use(config => {
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers.Authorization = `Bearer ${userStore.token}`
        }
        return config
    }, error => {
        return Promise.reject(error)
    })

    // 响应拦截器
    http.interceptors.response.use(
        response => {
            const res = response.data
            const router = useRouter()

            if (response.config.url.includes('/register') && res.code === 200) {
                ElMessage.success('注册成功！即将跳转登录页面')
                setTimeout(() => {
                    router.push({
                        name: 'Login',
                        query: {
                            fromRegister: 'true',
                            username: response.config.data?.username || ''
                        }
                    })
                }, 1500)
                return res
            }

            if (res.code !== 200) {
                ElMessage.error(res.message || 'Error')
                return Promise.reject(new Error(res.message || 'Error'))
            }
            return res
        },
        error => {
            const router = useRouter()
            let errorMessage = '请求失败'

            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        errorMessage = '登录已过期，请重新登录'
                        router.push('/login')
                        break
                }
            }
            ElMessage.error(errorMessage)
            return Promise.reject(error)
        }
    )
}

// 初始化拦截器
setupInterceptors()

// ==================== 请求工具 ====================
export const useRequest = () => {
    const request = (config) => http({
        ...config,
        headers: {
            'Content-Type': 'application/json',
            ...config.headers
        }
    })

    const get = (url, params) => request({ url, method: 'get', params })
    const post = (url, data) => request({ url, method: 'post', data })

    return { request, get, post }
}

// ==================== API模块 ====================
export const AuthAPI = {
    login: (data) => http.post('/login', data),
    register: (data) => http.post('/register', data)
}

export default http
